<template>
    <!-- 登录对话框 -->
    <el-dialog center title="注册" :visible.sync="dialogVisible" width="30%" class="dialog-register"
               :before-close="handleClose">
      <!-- 登录表单内容 -->
     <div class="dialog-form" >
       <el-form ref="userForm" :model="registerForm" :rules="rules" label-width="80px" class="register-form">
         <el-form-item label="昵称" prop="nickName">
           <el-input v-model="registerForm.nickName" autocomplete="off" placeholder="请输入昵称"
                     prefix-icon="el-icon-cloudy" style="width: 300px"></el-input>
         </el-form-item>

         <el-form-item label="姓名" prop="name">
           <el-input v-model="registerForm.name" autocomplete="off" placeholder="请输入姓名"
                     prefix-icon="el-icon-cloudy" style="width: 300px"></el-input>
         </el-form-item>

         <el-form-item label="邮箱" prop="email">
           <el-input v-model="registerForm.email" autocomplete="off" placeholder="请输入邮箱" prefix-icon="el-icon-user"
                     style="width: 300px"></el-input>
         </el-form-item>
         <!-- 密码输入框，仅在密码登录时显示 -->
         <el-form-item label="密码" prop="password">
           <el-input type="password" v-model="registerForm.password" placeholder="请输入密码" prefix-icon="el-icon-lock"
                     style="width: 300px" autocomplete="off"></el-input>
         </el-form-item>
         <el-form-item label="确认密码" prop="confirmPassword">
           <el-input type="password" v-model="registerForm.confirmPassword" placeholder="请再次输入密码"
                     prefix-icon="el-icon-lock" style="width: 300px" autocomplete="off"></el-input>
         </el-form-item>

         <el-form-item label="账号类型" prop="accountType">
           <el-select prefix-icon="el-icon-user" v-model="registerForm.accountType" placeholder="请选择账号类型" style="width: 300px">
             <el-option label="教师" value="1"></el-option>
             <el-option label="学生" value="2"></el-option>
           </el-select>
         </el-form-item>
         <!-- 验证码输入框，仅在验证码登录时显示 -->
         <el-form-item label="验证码" prop="code">
           <el-input placeholder="请输入验证码" v-model="registerForm.code" prefix-icon="el-icon-chat-round"
                     style="width: 300px" autocomplete="off">
             <template #append>
               <el-button :disabled="countdown > 0" @click="sendVerificationCode()" size="small">
                 {{ countdown > 0 ? `${countdown} 秒` : '获取验证码' }}
               </el-button>
             </template>
           </el-input>
         </el-form-item>

         <el-form-item>
           <el-button type="primary" @click="handleregister" class="register-btn">注册</el-button>
         </el-form-item>

       </el-form>
     </div>
    </el-dialog>
</template>


<script>
export default {
  data() {
    return {
      dialogVisible: false, // 控制对话框显示与隐藏
      registerForm: {},
      countdown: 0, // 添加倒计时初始值
      agreement: false, // 同意协议的状态
      rules: {
        nickName: [
          {required: true, message: '请输入昵称', trigger: 'blur'},
          {min: 3, max: 10, message: '昵称长度在 3 到 10 个字符', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'},
          {min: 2, max: 10, message: '昵称长度在 2 到 10 个字符', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 12, message: '密码长度在 6 到 12 个字符', trigger: 'blur'}
        ],
        confirmPassword: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 12, message: '密码长度在 6 到 12 个字符', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
          {len: 6, message: '验证码长度为 6 个字符', trigger: 'blur'}
        ],
        accountType: [
          {required: true, message: '请选择账号类型', trigger: 'blur'}
        ]
      },
    }
  },
  methods: {
    handleregister() {
      this.$refs['userForm'].validate((valid) => {
        if (valid) {  // 表单校验合法
          if (!this.registerForm.email) {
            this.$message.error('邮箱不能为空');
            return;
          }

          if (!this.registerForm.accountType) {
            this.$message.error('请选择对应的账号类型');
            return;
          }


          if (!this.validateEmail(this.registerForm.email)) {
            this.$message.error('请输入有效的邮箱');
          } else if (this.registerForm.password !== this.registerForm.confirmPassword) {
            this.$message.error('两次密码输入不一致');
          } else {
            if (this.registerForm.accountType==='1'){
              this.request.post('teacher/teacher/register', this.registerForm)
                  .then(res => {
                    if (res.code === 200) {
                      this.$message.success(res.message);
                      this.dialogVisible = false;
                      this.registerForm = {}
                      this.countdown = 0
                    }
                  })
            }else if (this.registerForm.accountType==='2'){
              this.request.post('student/student/register', this.registerForm)
                  .then(res => {
                    if (res.code === 200) {
                      this.$message.success(res.message);
                      this.dialogVisible = false;
                      this.registerForm = {}
                      this.countdown = 0
                    }
                  })
            }

          }
        } else {
          return false;
        }
      });


    },
    startCountdown() {
      if (this.countdown > 0) return; // 如果已经在倒计时中，则不再重新开始
      this.countdown = 60; // 假设倒计时60秒
      const intervalId = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(intervalId);
        }
      }, 1000);
    },
    validateEmail(email) {
      const regex = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      return regex.test(email);
    },
    validatePassword(password) {
      const regex = /^(?=.*[a-zA-Z])(?=.*\d).+$/; // 正则表达式，要求密码至少包含一个字母和一个数字
      return regex.test(password);
    },
    sendVerificationCode() {

      if (!this.registerForm.email) {
        this.$message.error('邮箱不能为空');
        return;
      }

      if (!this.registerForm.accountType) {
        this.$message.error('请选择对应的账号类型');
        return;
      }

      if (!this.validatePassword.password ||  !this.validatePassword.confirmPassword ){
        this.$message.error('密码必须包含数字和字母');

      }

      // 校验邮箱格式是否正确
      if (!this.validateEmail(this.registerForm.email)) {
        this.$message.error('请输入有效的邮箱地址');
        return;
      }


      // 向后端发送请求获取验证码
      if (this.registerForm.email.length!==0){
        if (this.registerForm.accountType === '1') {
          this.request.get('/teacher/teacher/sendCode/' + this.registerForm.email)
              .then(response => {
                console.log(response)
                if (response.code === 200) {
                  this.startCountdown();
                  this.$message.success(response.message)
                } else if (response.code === 400) {
                  this.$message.error(response.message)

                }
              })
              .catch(error => {
                console.error('发送验证码失败', error);
              });
        }else if (this.registerForm.accountType === '2'){
          this.request.get('/student/student/sendCode/' + this.registerForm.email)
              .then(response => {
                console.log(response)
                if (response.code === 200) {
                  this.startCountdown();
                  this.$message.success(response.message)
                } else if (response.code === 400) {
                  this.$message.error(response.message)

                }
              })
              .catch(error => {
                console.error('发送验证码失败', error);
              });
        }

      }else if (this.registerForm.email.length===0) {
        this.$message.error('注册邮箱不能为空')

      }

    },
    handleClose(done) {
      this.dialogVisible = false; // 关闭对话框
      this.$nextTick(() => {
        this.$refs['userForm'].resetFields(); // 重置表单字段
        this.registerForm = {}; // 清空表单数据
        this.countdown = 0; // 重置验证码倒计时
        done(); // 关闭对话框
      });
    }
  }
}
</script>
<style scoped>

.dialog-register {
  border-radius: 10px;
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.15);
}
.dialog-form{
  //margin-left: 20px;
  //padding-left: 30px;
  width: 100%;
  border-radius: 7px;
  background-color: #FFFFFF;
  display: flex;
  justify-content: center;
  align-items: center;
}
>>>.el-dialog__header{
  background: linear-gradient(140deg, #a1c4fd, #c2e9fb, #f1f2b5);
}
>>>.el-dialog__body{
  background: linear-gradient(120deg, #a1c4fd, #c2e9fb, #f1f2b5);
}

.register-form {
  padding: 20px;
}

.register-btn {
  padding: 10px 0;
  border-radius: 5px;
  font-size: 16px;
  background-color: #409EFF;
  border-color: #409EFF;
  width: 200px;
  transition: background-color .3s, border-color .3s;
  margin-left: 25px;
}

.register-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}


</style>